// SPDX-License-Identifier: GPL-2.0
/*
 * gpadc_csp.c - gpadc csp operation
 *
 * Copyright (C) 2016-2018, LomboTech Co.Ltd.
 * Author: lomboswer <lomboswer@lombotech.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#include <mach/csp.h>

#include "csp_gpadc.h"

#define GPADC_REF_ID		0x17

/* Set GPADC enable */
void csp_gpadc_set_en(void *base, u32 en)
{
	reg_gpadc_gpen_t reg;

	reg.val = READREG32(base + GPADC_GPEN_OFF);
	reg.bits.gen = en;

	WRITEREG32(base + GPADC_GPEN_OFF, reg.val);
}

/* Set GPADC calibration enable */
void csp_gpadc_set_cali_en(void *base, u32 en)
{
	reg_gpadc_gpen_t reg;

	reg.val = READREG32(base + GPADC_GPEN_OFF);
	reg.bits.cen = en;

	WRITEREG32(base + GPADC_GPEN_OFF, reg.val);
}

/* Get GPADC calibration data */
u32 csp_gpadc_get_cail_data(void *base)
{
	reg_gpadc_cdat_t reg;

	reg.val = READREG32(base + GPADC_CDAT_OFF);
	return reg.bits.dat;
}

void csp_set_sample_time(void *base)
{
	reg_gpadc_dbg0_t reg0;
	reg_gpadc_dbg1_t reg1;
	void *dbg0_addr = base + 0x4;
	void *dbg1_addr = base + 0x8;

	reg0.val = readl(dbg0_addr);
	reg0.bits.dbg_en = 1;
	writel(reg0.val, dbg0_addr);

	reg1.val = readl(dbg1_addr);
	reg1.bits.kvalue = 0xfff;
	reg1.bits.mvalue = 0x100;
	reg1.bits.speed_up = 1;
	writel(reg1.val, dbg1_addr);

	reg0.val = readl(dbg0_addr);
	reg0.bits.dbg_en = 0;
	writel(reg0.val, dbg0_addr);
}

void csp_set_ldo(void *base)
{
	reg_gpadc_dbg0_t reg0;
	void *dbg0_addr = base + 0x4;
	u32 efuse_val;

	efuse_val = (u32)csp_get_efuse_value(GPADC_REF_ID);

	if (efuse_val != 0) {
		reg0.val = readl(dbg0_addr);
		reg0.bits.dbg_en = 1;
		writel(reg0.val, dbg0_addr);

		reg0.val = readl(dbg0_addr);
		reg0.bits.cali_ldo = efuse_val;
		writel(reg0.val, dbg0_addr);

		reg0.val = readl(dbg0_addr);
		reg0.bits.dbg_en = 0;
		writel(reg0.val, dbg0_addr);
	} else {
		PRT_DBG("efuse_val is 0x%x, use default\n", efuse_val);
	}
}

